TRANS_READY	BIT	01H
ORDEN_PEND	BIT	02H
	
BUFER		EQU	030H

BUFERP		EQU	03AH
TEMP		EQU	03BH
LED		EQU	P2.0	
	
	ORG 0000H

	
	LJMP	START

	org 0023H
LJMP	RTI_RS232


			
	
ORG	0100H

ENCENDER_LED:
		CLR	LED
		RET
APAGAR_LED:	SETB	LED
		RET
SAY_HELLO:	MOV	DPH,#HIGH STR_HELLO
		MOV	DPL,#LOW STR_HELLO
		LCALL	WRITE_STRING
	
		RET
		
	
	
	
COMPARAR_BUFER:
		MOV	A,#0
		MOVC	A,@A+DPTR
		MOV	R0,#BUFER
		MOV	TEMP,@R0
		CJNE	A,TEMP,COMPARAR_BUFER_NOT	
		INC	R0
		INC	DPTR

BUCLE_COMPARAR_BUFER:
		MOV	A,#0
		MOVC	A,@A+DPTR
		MOV	R1,A
		MOV	A,@R0
		CJNE	R1,#0FFH,BC_COMPARAR_BUFER_ST0
		LJMP	COMPARAR_BUFER_YES
BC_COMPARAR_BUFER_ST0:	
		MOV	TEMP,R1
		CJNE	A,TEMP,COMPARAR_BUFER_NOT
		INC	DPTR
		INC	R0
		LJMP	BUCLE_COMPARAR_BUFER
	

	
COMPARAR_BUFER_NOT:
		MOV	R1,#0
		RET
COMPARAR_BUFER_YES:
		MOV	R1,#1
		RET

	
EJECUTAR_BUFER:
	
		MOV	DPL,#LOW ON
		MOV	DPH,#HIGH ON
		LCALL	COMPARAR_BUFER
		CJNE	R1,#1,EB_ST0
		LCALL	ENCENDER_LED
		JMP	EJECUTAR_BUFER_END
	
EB_ST0:		MOV	DPL,#LOW OFF
		MOV	DPH,#HIGH OFF
		LCALL	COMPARAR_BUFER
		CJNE	R1,#1,EB_ST1
		LCALL	APAGAR_LED
		JMP	EJECUTAR_BUFER_END
EB_ST1:		MOV	DPL,#LOW HELLO
		MOV	DPH,#HIGH HELLO
		LCALL	COMPARAR_BUFER
		CJNE	R1,#1,EB_ST2
		LCALL	SAY_HELLO
		JMP	EJECUTAR_BUFER_END
EB_ST2:		NOP	
EJECUTAR_BUFER_END:	
						
		RET
	
	

RTI_RS232:
		PUSH	PSW
		PUSH	ACC
		SETB	RS0
		SETB	RS1
		
		JNB	RI,RTI_RS_WRITE
RTI_RS_READ:	CLR	RI
		MOV	A,SBUF
		MOV	SBUF,A
		JNB	TI,$
		CLR	TI
		CJNE	A,#00DH,RTI_RS_READ_ST0
		SETB	ORDEN_PEND
		MOV	BUFERP,#BUFER
		LJMP	RTI_RS_END
RTI_RS_READ_ST0:	
		MOV	R0,BUFERP
		CJNE	R0,#BUFERP,RTI_RS_READ_ST1
		MOV	BUFERP,#BUFER
		MOV	R0,#BUFER

RTI_RS_READ_ST1:		
		MOV	@R0,A
		INC	R0
		MOV	BUFERP,R0
		LJMP	RTI_RS_END	

	
RTI_RS_WRITE:	CLR	TI
		SETB	TRANS_READY

RTI_RS_END:	POP	ACC
		POP	PSW
		RETI


	;; 
WRITE_BYTE:	JNB	TRANS_READY,$
		MOV	SBUF,A
		CLR	TRANS_READY
		RET
	
	
WRITE_STRING:
	MOV	A,#0
	MOVC	A,@A+DPTR
	INC	DPTR
	CJNE	A,#0FFH,WT_STAGE1
	LJMP	WRITE_STRING_END
WT_STAGE1:
	LCALL	WRITE_BYTE
	JMP	WRITE_STRING
WRITE_STRING_END:

		RET
	
	

	
	
	INIT_RS232:
	MOV	TH1,#243
	MOV	TMOD,#020H
	MOV	PCON,#080H
	SETB	TR1
	MOV	SCON,#050H
	MOV	BUFERP,#BUFER
	SETB	TRANS_READY
	SETB	ES
	SETB	EA
	RET

START:
	LCALL INIT_RS232
	MOV	DPH, #HIGH STR_WELCOME
	MOV	DPL, #LOW STR_WELCOME
	LCALL	WRITE_STRING
	

ETI:	JNB	ORDEN_PEND, BC_STAGE0
	LCALL	EJECUTAR_BUFER
	CLR	ORDEN_PEND
BC_STAGE0:
	
	JMP	ETI


	
ORG 1000H
STR_WELCOME:	DB	'< Comandos: encender, apagar, hello >',00Dh,0FFh
STR_HELLO:	DB	'Nos conocemos?',00DH,0FFh
	

	
ORG 1D00H
ON:		DB	'encender',0FFH
OFF:		DB	'apagar',0FFH
HELLO:		DB	'hello',0FFH

	
	
	END



	

